<template lang="pug">
.list(v-loading="loading")
  .list-container
    .list-header
      .list-header-title 图片册列表
      .list-header-btn
        el-button(type="primary" size="small" @click="uploadPhoto") 上传图片
    .list-body
      .article-list(v-if="list.length")
        .article-item(v-for="item in list")
          .article-item-hover
            .article-item-hover-hd
              .article-item-checkbox(:class="!item.isChecked ? 'checked' : ''")
                el-checkbox(v-model="item.isChecked" @change="changeArticle($event, item)")
              .article-item-btns.checked
                .article-item-btn(@click="perview(item)")
                  i.el-icon-search
                el-popover(
                  trigger="hover"
                )
                  .pop-item(@click="rename(item)") 重命名
                  .pop-item(:id="`photo_${item.photoId}`" @click="moveGroup(item)") 移动图片册
                  .pop-item(@click="delSingleArticle(item)") 删除
                  .article-item-btn(slot="reference")
                    i.el-icon-more
          .article-item-cover(:style="`background-image: url(${item.fileUrl})`")
          .article-item-name(v-if="!item.showInput") {{item.photoName}}
          .article-item-name(v-else)
            el-input(v-model="item.photoName" v-focus @blur="blurInput(item)" @change="changeSourceName(item)" placeholder="请输入名称")
      .article-empty(v-else)
        img(src="../../static/images/empty_.png")
        .article-empty-txt 暂无数据...
      .article-footer(v-if="list.length")
        .article-handles
          .article-handles-container(v-if="selections.length")
            el-checkbox(v-model="checkAll" @change="changeAll") 全选
            .article-handle-info 已选择 {{selections.length}} 项内容
            .article-handle-cancel(@click="cancelAll") 取消选择
            .article-handle-ft
              el-button(size="small" @click="delSource") 删除
              el-button#batch-move(size="small" @click="batchMove") 移动
        el-pagination(
          background
          layout="prev, pager, next, jumper"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="currentChange"
        )
  el-popover(
    v-model="visible"
    tigger="click"
    width="300"
    ref="spacePopover"
  )
    .pop-container
      .pop-group-list
        .group-item(v-for="space in imageList")
          .group-item-bd(:class="space.isChecked ? 'active' : ''" @click="selectSpace(space)") {{space.albumName}}
      .pop-footer
        el-button(size="small" type="primary" @click="confirmMove") 确定
        el-button(size="small" @click="visible = false") 取消
  photo-dialog(:show="showPhotoDialog" :albumId="albumId" @confirm="confirmPhoto" @close="closePhoto")
</template>

<script>
import { getPhotoList, deletePhotoBatch, saveOrUpdateImage, getImageList, movePhotoBatch } from 'api'
import { mapActions } from 'vuex'
import photoDialog from "./photoDialog"
export default {
  name: 'photoList',
  components: {
    photoDialog
  },
  data () {
    return {
      albumId: '',
      list: [],
      loading: false,
      pageSize: 14,
      currentPage: 1,
      total: 0,
      isHidden: false,
      isMore: false,
      checkAll: false,
      selections: [],
      currentItem: {},
      fileAgain: null,
      showPhotoDialog: false,
      visible: false,
      imageList: []
    }
  },
  methods: {
    ...mapActions([
      'changePreviewModal'
    ]),
    changeAll (value) {
      this.selections = []
      this.list.forEach(item => {
        item.isChecked = value
        this.changeArticle(value, item)
      })
    },
    cancelAll () {
      this.selections = []
      this.list.forEach(item => {
        item.isChecked = false
      })
    },
    changeArticle (value, item) {
      if (value) {
        this.selections.push(item)
      } else {
        let index = this.selections.findIndex(row => row.photoId === item.photoId)
        if (index > -1) {
          this.selections.splice(index, 1)
        }
      }
    },
    uploadPhoto () {
      this.showPhotoDialog = true
    },
    confirmPhoto () {
      this.getList()
      this.showPhotoDialog = false
    },
    closePhoto () {
      this.showPhotoDialog = false
    },
    currentChange (page) {
      this.currentPage = page
      this.getList()
    },
    perview (item) {
      this.changePreviewModal({ show: true, url: item.fileUrl })
    },
    delSource () {
      this.$confirm(`确定删除选择的这些图片吗？`, '提示', {
        confirmButtonText: '删除'
      }).then(async () => {
        try {
          let ids = this.selections.map(item => item.photoId)
          await this.$axios.post(deletePhotoBatch, { content: { ids } })
          this.$message.success('删除成功！')
          this.currentPage = 1
          this.getList()
        } catch (err) {
          this.$message.error(err.message || err.ResultSet.errors)
        }
      })
    },
    delSingleArticle (item) {
      this.$confirm(`确定将此图片从该图片册删除吗？`, '提示', {
        confirmButtonText: '删除'
      }).then(async () => {
        try {
          this.loading = true
          let ids = [item.photoId]
          await this.$axios.post(deletePhotoBatch, { content: { ids } })
          this.$message.success('删除成功！')
          this.currentPage = 1
          this.getList()
          this.loading = false
        } catch (err) {
          this.loading = false
          this.$message.error(err.message || err.ResultSet.errors)
        }
      })
    },
    rename (item) {
      this.list.forEach(row => {
        row.showInput = false
      })
      item.showInput = true
    },
    blurInput (item) {
      item.showInput = false
    },
    async changeSourceName (item) {
      try {
        await this.$axios.post(saveOrUpdateImage, { content: { ...item } })
        item.showInput = false
        this.$message.success('修改成功！')
        this.getList()
      } catch (err) {
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    batchMove () {
      if(this.$refs && this.$refs.spacePopover) {
        this.$refs.spacePopover.referenceElm = document.getElementById(`batch-move`)
        this.$refs.spacePopover.doToggle()
      }
    },
    moveGroup (item) {
      this.currentItem = item
      if(this.$refs && this.$refs.spacePopover) {
        this.$refs.spacePopover.referenceElm = document.getElementById(`photo_${item.photoId}`)
        this.$refs.spacePopover.doToggle()
      }
    },
    selectSpace (item) {
      this.imageList.forEach(row => {
        row.isChecked = false
      })
      item.isChecked = true
    },
    async confirmMove () {
      try {
        this.loading = true
        let item = this.imageList.find(item => item.isChecked)
        let ids = []
        if (this.selections.length) {
          ids = this.selections.map(item => item.photoId)
        } else {
          ids = [this.currentItem.photoId]
        }
        await this.$axios.post(movePhotoBatch, { content: { albumId: item.albumId, ids: ids } })
        this.currentItem = {}
        this.getImageList()
        this.getList()
        if (this.selections.length) this.selections = []
        this.$refs.spacePopover.doClose()
        this.loading = false
      } catch (err) {
        console.log(err)
        this.loading = false
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getList () {
      try {
        this.selections = []
        this.loading = true
        const { ResultSet } = await this.$axios.post(getPhotoList, { content: { albumId: this.albumId, currentPage: this.currentPage, pageSize: this.pageSize } })
        if (ResultSet.userData.PhotosList.length) {
          ResultSet.userData.PhotosList.forEach(item => {
            item.showInput = false
            item.isChecked = false
          })
        }
        this.list = ResultSet.userData.PhotosList || []
        this.total = ResultSet.recordNumber
        this.loading = false
      } catch (err) {
        this.loading = false
        this.$message.error(err.message || err.ResultSet.errors)
      }
    },
    async getImageList () {
      try {
        const { ResultSet } = await this.$axios.post(getImageList, { content: { currentPage: 1, pageLines: 99999999 } })
        ResultSet.userData.PhotoAlbumList.forEach(item => {
          item.isChecked = false
        })
        this.imageList = ResultSet.userData.PhotoAlbumList.filter(item => item.albumId !== this.albumId)
      } catch (err) {
        console.log(err)
        this.$message.error(err.message || err.ResultSet.errors)
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.albumId = parseInt(to.params.id)
      vm.getList()
      vm.getImageList()
    })
  }
}
</script>

<style lang="scss" scoped>
.list {
  padding: 0 32px 16px;
  height: 100%;
}
.list-container {
  width: 100%;
  height: 100%;
  padding: 20px 24px;
  margin-bottom: 16px;
  background: #fff;
  border-radius: 4px;
}
.list-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.list-header-title {
  font-size: 16px;
  font-weight: bold;
  color: #363636;
}
.article-list {
  padding: 10px 12px;
  display: flex;
  flex-wrap: wrap;
  background: #fff;
}
.article-item {
  position: relative;
  margin: 0 6px 35px;
  &:hover {
    .checked {
      opacity: 1;
    }
  }
}
.article-item-hover {
  position: absolute;
  left: 0;
  top: 0;
  padding: 6px 12px;
  width: 100%;
  height: 100%;
}
.checked {
  opacity: 0;
}
.article-item-hover-hd {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.article-item-btns {
  display: flex;
  align-items: center;
}
.article-item-btn {
  width: 28px;
  height: 28px;
  border: 1px solid #DCDFE6;
  border-radius: 50%;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: 15px;
  cursor: pointer;
}
.article-item-cover {
  width: 200px;
  height: 200px;
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
}
.article-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px 20px;
  background: #fff;
}
.article-empty {
  padding-top: 80px;
  text-align: center;
}
.article-empty-txt {
  font-size: 16px;
  margin-top: 10px;
  color: #999;
}
.pop-item {
  padding: 10px 0;
  cursor: pointer;
}
.article-item-name {
  margin-top: 5px;
  padding: 10px 0;
  text-align: center;
  font-size: 14px;
  line-height: 16px;
  color: #363636;
}
.pop-group-list {
  display: flex;
  flex-wrap: wrap;
  max-height: 300px;
  overflow: overlay;
  .group-item {
    width: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    .group-item-bd {
      padding: 7px 16px;
      border-radius: 50px;
      color: #363636;
      font-size: 14px;
      margin-bottom: 10px;
      cursor: pointer;
      &.active {
        background: #FF2E42;
        color: #fff;
      }
    }
  }
}
.pop-footer {
  text-align: center;
}
.article-handles {
  background: #fff;
}
.article-handles-container {
  height: 48px;
  display: flex;
  align-items: center;
}
.article-handle-info {
  margin-left: 30px;
  font-size: 12px;
  color: #000;
}
.article-handle-cancel {
  font-size: 12px;
  color: #999;
  margin-left: 30px;
  cursor: pointer;
}
.article-handle-ft {
  margin-left: 10px;
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  .iconfont {
    font-size: 16px;
    color: #999;
    margin-left: 15px;
    cursor: pointer;
  }
}
</style>